const express = require("express")
const path = require("path")
const router = require("./router")
const bodyParser = require('body-parser')
const session = require('express-session')
const app = express()

//注册session
app.set('trust proxy', 1)
app.use(session({
    secret: 'keyboard cat',//加密字符串
    resave: false,
    saveUninitialized: true, //默认给客户端一个session,无论是否使用
    // cookie: { secure: true }
}))

//配置参数解析器
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))


//join  __dirname 会将相对路径改成绝对路径
app.use("/public/",express.static(path.join(__dirname,'./public/')))
app.use("/node_modules/",express.static(path.join(__dirname,"./node_modules/")))


//模板引擎
app.engine('html', require('express-art-template'));
//设置views对应的路径
app.set('views', path.join(__dirname, "views"));


//拦截器(中间件)
app.use(function (req, res, next) {
    let url = req.url;
    if (["/register", "/login", "/logOut"].indexOf(url) === -1) {
        if (req.session.loginUser) {
            next();
        } else {
            return res.redirect('/login');
        }
    } else {
        next();//调用下一个中间件
    }
});


//路由
app.use(router)


//错误处理器  next(xxx) 传入参数就会调用错误处理器 ,需放在路由后面
app.use((err, req, res, next) => {
    res.status(500).send(err)
})


//404拦截器
app.use(function (req, res, next) {
    res.send("404")
});


app.listen(8080,function () {
    console.log("server is start...");
})